package com.qiantu.phone.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

/**
 * Created by luzx on 2019/05/16.
 */
public class ClickImageView extends AppCompatImageView {
    private ScaleAnimation amplifyAnimation;

    private ScaleAnimation reduceAnimation;

    public ClickImageView(Context context) {
        super(context);
        createAnimation();
    }

    public ClickImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        createAnimation();
    }

    public ClickImageView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        createAnimation();
    }

    private void createAnimation(){
        if(amplifyAnimation != null){
            return;
        }
        amplifyAnimation = new ScaleAnimation(1, 0.95f, 1, 0.95f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        amplifyAnimation.setDuration(120);
        //设置持续时间
        amplifyAnimation.setFillAfter(true);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        amplifyAnimation.setRepeatCount(0);
        //设置循环次数，0为1次

        if(reduceAnimation != null){
            return;
        }
        reduceAnimation = new ScaleAnimation(0.95f, 1, 0.95f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        reduceAnimation.setDuration(120);
        //设置持续时间
        reduceAnimation.setFillAfter(true);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        reduceAnimation.setRepeatCount(0);
        //设置循环次数，0为1次
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(isEnabled() && isClickable()){
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    reduceAnimation.cancel();
                    startAnimation(amplifyAnimation);
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    amplifyAnimation.cancel();
                    startAnimation(reduceAnimation);
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(amplifyAnimation != null){
            amplifyAnimation.cancel();
        }
        if(reduceAnimation != null){
            reduceAnimation.cancel();
        }
    }
}
